package cn.yuanqiao.archive.detection.util;


import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class EncryptionUtil {



    public static String getMD5Hash(String filePath) throws NoSuchAlgorithmException {
        // 使用MD5创建MessageDigest对象
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 获取文件输入流
        try (InputStream is = new FileInputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int read = 0;

            // 读取文件内容并更新哈希值
            while ((read = is.read(buffer)) != -1) {
                md.update(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取最终的哈希值
        byte[] digest = md.digest();
        return bytesToHex(digest);
    }
    public static String getSM3Hash(String filePath) throws IOException {
        File file=new File(filePath);
        Security.addProvider(new BouncyCastleProvider());
        Digest digest = new SM3Digest();
        byte[] buffer = new byte[1024];
        int read;

        try (FileInputStream fis = new FileInputStream(file)) {
            while ((read = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, read);
            }
        }

        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);

        return bytesToHex(hash);
    }
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }




}
